<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ $product->name }} - 商品详情</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
    <style>
        /* 基础样式 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
            color: #333;
            padding-bottom: 120px;
            -webkit-tap-highlight-color: transparent;
        }

        .product-detail-container {
            max-width: 100%;
            padding: 15px;
        }

        /* 商品图片轮播 */
        .swiper-container {
            width: 100%;
            height: 300px;
            margin-bottom: 20px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .swiper-slide {
            display: flex;
            justify-content: center;
            align-items: center;
            background: #f8f9fa;
        }

        .swiper-slide img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        /* 商品信息卡片 */
        .product-card {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .product-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
            line-height: 1.4;
        }

        .product-description {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
            line-height: 1.5;
        }

        .product-info-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 15px;
        }

        .product-price {
            color: #e63946;
            font-size: 24px;
            font-weight: bold;
        }

        .product-stock {
            color: #666;
            font-size: 14px;
        }

        /* 规格选择 */
        .variants-container {
            margin: 15px 0;
        }

        .variant-label {
            margin-bottom: 10px;
            font-weight: bold;
            color: #333;
            font-size: 16px;
        }

        .variant-selection {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .variant-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 20px;
            background: white;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
        }

        .variant-btn:hover {
            border-color: #07C160;
            color: #07C160;
        }

        .variant-btn.active {
            background-color: #07C160;
            color: white;
            border-color: #07C160;
        }

        /* 数量选择 */
        .quantity-section {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .quantity-label {
            color: #333;
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 15px;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .quantity-buttons {
            display: flex;
            align-items: center;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
        }

        .quantity-btn {
            width: 40px;
            height: 40px;
            background: #f8f9fa;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
            transition: background-color 0.2s;
        }

        .quantity-btn:hover {
            background: #e9ecef;
        }

        .quantity-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .quantity-input {
            width: 60px;
            height: 40px;
            text-align: center;
            border: none;
            border-left: 1px solid #ddd;
            border-right: 1px solid #ddd;
            font-size: 16px;
            background: #fff;
        }

        /* 商品详情 */
        .product-detail-section {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .detail-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }

        .detail-content {
            color: #666;
            line-height: 1.6;
        }

        /* 底部操作栏 */
        .bottom-action-bar {
            position: fixed;
            bottom: 60px;
            left: 0;
            right: 0;
            background: #fff;
            padding: 15px;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 200;
            display: flex;
            gap: 10px;
        }

        .action-btn {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s, transform 0.2s;
        }

        .add-to-cart-btn {
            background: #07C160;
            color: white;
        }

        .add-to-cart-btn:hover {
            background: #05a854;
            transform: translateY(-2px);
        }

        .buy-now-btn {
            background: #e63946;
            color: white;
        }

        .buy-now-btn:hover {
            background: #c1121f;
            transform: translateY(-2px);
        }

        .action-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
        }

        .action-btn:active {
            transform: translateY(0);
        }

        /* 底部导航栏 */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 60px;
            background: #fff;
            display: flex;
            justify-content: space-around;
            align-items: center;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 200;
            padding: 0 5px;
        }

        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #7f8c8d;
            font-size: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .nav-item.active {
            color: #07C160;
            background: rgba(7, 193, 96, 0.1);
        }

        .nav-icon {
            font-size: 20px;
            margin-bottom: 3px;
        }

        .cart-badge {
            position: absolute;
            top: 0;
            right: 0;
            background: #e74c3c;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        /* 通知样式 */
        .notification {
            position: fixed;
            bottom: 80px;
            left: 50%;
            transform: translateX(-50%);
            background: #07C160;
            color: white;
            padding: 12px 24px;
            border-radius: 30px;
            z-index: 300;
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
            animation: slideIn 0.3s ease-out;
            font-weight: 500;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translate(-50%, 20px);
            }
            to {
                opacity: 1;
                transform: translate(-50%, 0);
            }
        }
    </style>
</head>

<body>
    <div class="product-detail-container">
        <!-- 商品图片轮播 -->
        <div class="swiper-container product-swiper">
            <div class="swiper-wrapper">
                @if($product->media->isNotEmpty())
                @foreach($product->media as $media)
                <div class="swiper-slide">
                    <img src="{{ $media->getUrl() }}" alt="{{ $product->name }}">
                </div>
                @endforeach
                @else
                <div class="swiper-slide">
                    <img src="{{ asset('images/default_product.jpg') }}" alt="默认图片">
                </div>
                @endif
            </div>
            <div class="swiper-pagination"></div>
        </div>

        <!-- 商品基本信息 -->
        <div class="product-card">
            <h1 class="product-title">{{ $product->name }}</h1>
            <p class="product-description">{{ $product->description }}</p>
            <div class="product-info-row">
                <span class="product-price">¥{{ number_format($product->price, 2) }}</span>
                <span class="product-stock">库存: {{ $product->stock }}件</span>
            </div>

            <!-- 添加规格选择区域 -->
            @if(isset($product->variants) && $product->variants->isNotEmpty())
            <div class="variants-container">
                <div class="variant-label">规格：</div>
                <div class="variant-selection">
                    @foreach($product->variants as $variant)
                    <button class="variant-btn"
                        data-variant-id="{{ $variant->id }}"
                        data-price="{{ $variant->price }}">
                        {{ $variant->name }}
                    </button>
                    @endforeach
                </div>
            </div>
            @endif
        </div>

        <!-- 数量选择 -->
        <div class="quantity-section">
            <div class="quantity-label">数量</div>
            <div class="quantity-control">
                <div class="quantity-buttons">
                    <button class="quantity-btn minus" type="button">-</button>
                    <input type="number" id="quantity" value="1" min="1" max="{{ $product->stock }}" class="quantity-input">
                    <button class="quantity-btn plus" type="button">+</button>
                </div>
            </div>
        </div>

        <!-- 商品详情 -->
        <div class="product-detail-section">
            <h2 class="detail-title">商品详情</h2>
            <div class="detail-content">
                {!! $product->detail ?? '暂无详情' !!}
            </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-action-bar">
            <button class="action-btn add-to-cart-btn"
                data-product-id="{{ $product->id }}">
                加入购物车
            </button>
            <button class="action-btn buy-now-btn"
                data-product-id="{{ $product->id }}"
                style="background-color: #e63946; color: white; border: none; border-radius: 20px; padding: 12px 20px; font-size: 16px; font-weight: 500; cursor: pointer; transition: background-color 0.2s, transform 0.2s;">
                购买
            </button>
        </div>
        
        <style>
            .buy-now-btn:hover:not(:disabled) {
                background-color: #c1121f;
                transform: translateY(-2px);
            }
            
            .buy-now-btn:active {
                transform: translateY(0);
            }
            
            .buy-now-btn:disabled {
                background-color: #95a5a6;
                cursor: not-allowed;
            }
        </style>
    </div>

    <!-- 微信分享配置 -->
    <script>
        wx.config({
            debug: false,
            appId: '{{ $wxConfig["appId"] }}',
            timestamp: '{{ $wxConfig["timestamp"] }}',
            nonceStr: '{{ $wxConfig["nonceStr"] }}',
            signature: '{{ $wxConfig["signature"] }}',
            jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData'
            ]
        });

        wx.ready(function() {
            // 自定义"分享给朋友"及"分享到朋友圈"按钮内容
            wx.updateAppMessageShareData({
                title: '{{ addslashes($product->name) }}',
                desc: '{{ addslashes($product->description) }}',
                link: window.location.href,
                imgUrl: '{{ $product->media->isNotEmpty() ? $product->media->first()->getUrl() : asset("images/default_product.jpg") }}'
            });

            wx.updateTimelineShareData({
                title: '{{ addslashes($product->name) }}',
                link: window.location.href,
                imgUrl: '{{ $product->media->isNotEmpty() ? $product->media->first()->getUrl() : asset("images/default_product.jpg") }}'
            });
        });

        // 规格选择逻辑
        const variantBtns = document.querySelectorAll('.variant-btn');
        // 默认选中第一个规格
        if (variantBtns.length > 0) {
            variantBtns[0].classList.add('active');
            const defaultPrice = variantBtns[0].dataset.price;
            document.querySelector('.product-price').textContent = '¥' + parseFloat(defaultPrice).toFixed(2);
        }

        variantBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 移除所有按钮的active类
                document.querySelectorAll('.variant-btn').forEach(b => b.classList.remove('active'));
                // 为当前按钮添加active类
                this.classList.add('active');
                // 更新显示的价格
                const price = this.dataset.price;
                document.querySelector('.product-price').textContent = '¥' + parseFloat(price).toFixed(2);
            });
        });

        // 数量加减逻辑（添加库存检查）
        document.querySelectorAll('.quantity-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const input = document.getElementById('quantity');
                let value = parseInt(input.value);
                const maxStock = parseInt('{{ $product->stock }}');

                if (this.classList.contains('minus') && value > 1) {
                    input.value = value - 1;
                } else if (this.classList.contains('plus') && value < maxStock) {
                    input.value = value + 1;
                }

                // 确保不超过最大库存
                input.value = Math.min(parseInt(input.value), maxStock);
            });
        });

        // 输入框直接输入的处理
        document.getElementById('quantity').addEventListener('change', function() {
            const maxStock = parseInt('{{ $product->stock }}');
            let value = parseInt(this.value) || 1;

            if (value < 1) value = 1;
            if (value > maxStock) value = maxStock;

            this.value = value;
        });

        // 购买按钮点击事件
        document.querySelector('.buy-now-btn')?.addEventListener('click', function() {
            // 禁用按钮防止重复点击
            this.disabled = true;
            this.textContent = '添加中...';
            
            const productId = this.getAttribute('data-product-id');
            let quantity = parseInt(document.getElementById('quantity').value) || 1;
            const maxStock = parseInt('{{ $product->stock }}');

            // 最终确认数量不超过库存
            quantity = Math.min(quantity, maxStock);
            if (quantity < 1) quantity = 1;

            // 获取选中的商品规格
            let variantId = null;
            const activeVariant = document.querySelector('.variant-btn.active');
            if (activeVariant) {
                variantId = activeVariant.getAttribute('data-variant-id');
            }

            // 先将商品添加到购物车
            axios.post('{{ route("wechat.service.account.cart.add") }}', {
                product_id: productId,
                quantity: quantity,
                variant_id: variantId
            }, {
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (response.data.success) {
                    // 显示成功通知
                    showNotification('✓ 已添加到购物车');
                    
                    // 短暂延迟后跳转到购物车页面
                    setTimeout(() => {
                        window.location.href = '{{ route("wechat.service.account.cart") }}';
                    }, 1000);
                } else {
                    showNotification('添加失败: ' + response.data.message);
                    // 恢复按钮状态
                    this.disabled = false;
                    this.textContent = '购买';
                }
            }).catch(error => {
                console.error('Error:', error);
                if (error.response && error.response.status === 401) {
                    showNotification('请先登录后再添加商品');
                    // 延迟跳转到登录页面
                    setTimeout(() => {
                        window.location.href = '{{ addslashes(route("wechat.service.account.login")) }}';
                    }, 1500);
                } else {
                    showNotification('网络异常，请重试');
                }
                // 恢复按钮状态
                this.disabled = false;
                this.textContent = '购买';
            });
        });

        // 加入购物车逻辑
        document.querySelector('.add-to-cart-btn').addEventListener('click', function() {
            const productId = this.dataset.productId;
            let quantity = parseInt(document.getElementById('quantity').value);
            const maxStock = parseInt('{{ $product->stock }}');

            // 最终确认数量不超过库存
            quantity = Math.min(quantity, maxStock);

            // 获取选择的规格（如果有）
            const activeVariant = document.querySelector('.variant-btn.active');
            const variantId = activeVariant ? activeVariant.dataset.variantId : null;

            // 禁用按钮防止重复点击
            const originalText = this.textContent;
            this.textContent = '添加中...';
            this.disabled = true;

            axios.post('{{ route("wechat.service.account.cart.add") }}', {
                product_id: productId,
                quantity: quantity,
                variant_id: variantId
            }, {
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (response.data.success) {
                    showNotification('✓ 已添加到购物车');
                    this.textContent = '✓ 已添加';
                    setTimeout(() => {
                        this.textContent = originalText;
                        this.disabled = false;
                    }, 2000);
                } else {
                    showNotification('添加失败: ' + response.data.message);
                    this.textContent = originalText;
                    this.disabled = false;
                }
            }).catch(error => {
                console.error('Error:', error);
                if (error.response && error.response.status === 401) {
                    showNotification('请先登录后再添加商品');
                    // 延迟跳转到登录页面
                    setTimeout(() => {
                        window.location.href = '{{ addslashes(route("wechat.service.account.login")) }}';
                    }, 1500);
                } else {
                    showNotification('网络异常，请重试');
                }
                this.textContent = originalText;
                this.disabled = false;
            });
        });

        // 显示通知
        function showNotification(message) {
            // 移除现有通知
            const existing = document.querySelector('.notification');
            if (existing) existing.remove();

            // 创建新通知
            const notification = document.createElement('div');
            notification.className = 'notification';
            notification.textContent = message;
            document.body.appendChild(notification);

            // 3秒后移除通知
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 2000);
        }

        // 底部导航栏点击事件
        document.addEventListener('DOMContentLoaded', function() {
            const navItems = document.querySelectorAll('.nav-item');
            
            navItems.forEach(item => {
                item.addEventListener('click', function() {
                    const route = this.getAttribute('data-route');
                    if (route) {
                        // 移除所有active类
                        navItems.forEach(nav => nav.classList.remove('active'));
                        // 添加active类到当前点击的项目
                        this.classList.add('active');
                        // 跳转到对应页面
                        window.location.href = route;
                    }
                });
            });
        });
    </script>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
        <div class="nav-item" data-route="{{ route('wechat.service.account.index') }}">
            <span class="nav-icon">🏠</span>
            <span>首页</span>
        </div>
        <div class="nav-item" data-route="{{ route('wechat.service.account.cart') }}">
            <span class="nav-icon">🛒</span>
            <span>购物车</span>
            @php
                $cartCount = app(\App\Services\CartService::class)->getCartCount();
            @endphp
            @if($cartCount > 0)
                <span class="cart-badge">{{ $cartCount }}</span>
            @endif
        </div>
        <div class="nav-item" data-route="{{ route('wechat.service.account.my') }}">
            <span class="nav-icon">👤</span>
            <span>我的</span>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化Swiper轮播
            new Swiper('.swiper-container', {
                loop: true,
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
                autoplay: {
                    delay: 3000,
                    disableOnInteraction: false,
                },
            });
        });
    </script>
</body>

</html>